package com.ssyc.student.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.PinyinComparator;
import com.ssyc.common.utils.PinyinUtils;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.SideBar;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StFriendsRvAdapter;
import com.ssyc.student.bean.AddressBookInfo;
import com.ssyc.student.bean.StFriendsInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--通讯录--好友Fragment
 * Created by Administrator on 2018/5/15 0015.
 */

public class StudentFriendsFragment extends LazyBaseFragment {

    //单例模式
    private static volatile StudentFriendsFragment friendsFragment;

    //加载布局
    private RelativeLayout rlLoading;

    //内容
    private RelativeLayout rlContent;

    //列表控件
    private RecyclerView rv;

    //下拉刷新
    private SmartRefreshLayout srf;

    //右侧的索引栏
    private SideBar sideBar;

    //中间的显示的文字
    private TextView dialog;

    //数据集合
    private List<StFriendsInfo> SourceDateList;

    //适配器
    private StFriendsRvAdapter adapter;

    //根据拼音来排列RecyclerView里面的数据类
    private PinyinComparator pinyinComparator;

    //空视图
    private View emptyView;

    public static StudentFriendsFragment newInstance() {
        return new StudentFriendsFragment();
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_friends;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
        showContent();

        //初始化控件
        initView(view);

        //初始化下拉刷新
        initSrf();

        //获取服务器数据
        http();
    }


    /**
     * 获取服务器数据的方法
     */
    private void http() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "13");
        map.put("c", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("platform", "8");
        HttpUtils.post(HttpAdress.GETADDRESSBOOK, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (!TextUtils.isEmpty(response)) {
                    AddressBookInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, AddressBookInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }

                    Log.i("test", "通讯录好友"+response);
                    if (null != info && "1".equals(info.getState())) {
                        //取出好友列表
                        List<AddressBookInfo.FriendlistBean> friendlist = info.getFriendlist();
                        if (null != friendlist && friendlist.size() != 0) {
                            rlContent.setVisibility(View.VISIBLE);
                            initRv(friendlist);
                        }
                    } else {
                        Log.i("test", "返回状态码是:" + info.getState());
                    }
                }

            }
        });
    }


    /**
     * 初始化View
     *
     * @param view
     */
    public void initView(View view) {
        rlLoading = view.findViewById(R.id.rl_loading_view);
        rlLoading.setVisibility(View.VISIBLE);
        //内容
        rlContent = view.findViewById(R.id.rl_content);
        rlContent.setVisibility(View.GONE);

        pinyinComparator = new PinyinComparator();
        rv = view.findViewById(R.id.rv);
        srf = view.findViewById(R.id.srf);
        sideBar = view.findViewById(R.id.sideBar);
        dialog = view.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧SideBar触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    ((LinearLayoutManager) rv.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                }

            }
        });
    }

    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, null);
    }

    /**
     * 初始化数据
     */
    private void initRv(List<AddressBookInfo.FriendlistBean> friendlist) {
        SourceDateList = filledData(friendlist);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        emptyView = View.inflate(getContext(), R.layout.base_rv_common_empty_view, null);
        adapter = new StFriendsRvAdapter(getContext(), R.layout.student_friend_item, SourceDateList);
        BqaManager.setRv(emptyView, getContext(), adapter, rv);
    }


    /**
     * 为RecyclerView填充数据
     *
     * @return
     */
    private List<StFriendsInfo> filledData(List<AddressBookInfo.FriendlistBean> friendlist) {
        List<StFriendsInfo> mSortList = new ArrayList<>();
        for (int i = 0; i < friendlist.size(); i++) {
            StFriendsInfo sortModel = new StFriendsInfo();
            //设置名称
            sortModel.setName(friendlist.get(i).getName());
            sortModel.setRole(friendlist.get(i).getRole());
            sortModel.setUserId(friendlist.get(i).getUser_id());
            sortModel.setHeadUrl(friendlist.get(i).getHeadimg());
            sortModel.setDescription(friendlist.get(i).getDescription());
            sortModel.setToken2(friendlist.get(i).getToken2());
            sortModel.setType(friendlist.get(i).getType());
            sortModel.setStatus(friendlist.get(i).getStatus());

            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(friendlist.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setLetters(sortString.toUpperCase());
            } else {
                sortModel.setLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;
    }
}
